package com.csj.mvvm.utils


import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
import java.io.*
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method


class SpUtil {

    /**
     * 保存在手机里面的文件名
     */
    lateinit var sp: SharedPreferences

    companion object {
        private var instance: SpUtil? = null
        fun getInstance() = instance ?: SpUtil().also { instance = it }
    }

    fun setContext(context: Context) {
        sp = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
    }

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param key
     * @param object
     */
    fun put(key: String?, obj: Any) {
        val editor = sp.edit()
        if (obj is String) {
            editor.putString(key, obj)
        } else if (obj is Int) {
            editor.putInt(key, obj)
        } else if (obj is Boolean) {
            editor.putBoolean(key, obj)
        } else if (obj is Float) {
            editor.putFloat(key, obj)
        } else if (obj is Long) {
            editor.putLong(key, obj)
        } else {
            editor.putString(key, obj.toString())
        }
        SharedPreferencesCompat.apply(editor)
    }


    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param key
     * @param defaultObject
     * @return
     */
    fun get(key: String?, defaultObject: Any?): Any? {
        if (defaultObject is String) {
            return sp.getString(key, defaultObject as String?)
        } else if (defaultObject is Int) {
            return sp.getInt(key, (defaultObject as Int?)!!)
        } else if (defaultObject is Boolean) {
            return sp.getBoolean(key, (defaultObject as Boolean?)!!)
        } else if (defaultObject is Float) {
            return sp.getFloat(key, (defaultObject as Float?)!!)
        } else if (defaultObject is Long) {
            return sp.getLong(key, (defaultObject as Long?)!!)
        }
        return null
    }

    /**
     * 移除某个key值已经对应的值
     */
    fun remove(key: String?) {
        val editor = sp.edit()
        editor.remove(key)
        SharedPreferencesCompat.apply(editor)
    }

    /**
     * 清除所有数据
     */
    fun clear() {
        val editor = sp.edit()
        editor.clear()
        SharedPreferencesCompat.apply(editor)
    }


    fun setObject(key: String?, obj: Any?) {
        val baos = ByteArrayOutputStream()
        var out: ObjectOutputStream? = null
        try {
            out = ObjectOutputStream(baos)
            out.writeObject(obj)
            val objectVal = String(Base64.encode(baos.toByteArray(), Base64.DEFAULT))
            val editor = sp.edit()
            editor.putString(key, objectVal)
            editor.commit()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                if (baos != null) {
                    baos.close()
                }
                out?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    fun <T> getObject(key: String?, clazz: Class<T>?): T? {
        if (sp.contains(key)) {
            val objectVal = sp.getString(key, null)
            val buffer = Base64.decode(objectVal, Base64.DEFAULT)
            val bais = ByteArrayInputStream(buffer)
            var ois: ObjectInputStream? = null
            try {
                ois = ObjectInputStream(bais)
                return ois.readObject() as T
            } catch (e: StreamCorruptedException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            } catch (e: ClassNotFoundException) {
                e.printStackTrace()
            } finally {
                try {
                    if (bais != null) {
                        bais.close()
                    }
                    ois?.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return null
    }


    /**
     * 返回所有的键值对
     *
     * @return
     */
    fun getAll(): Map<String?, *>? {
        return sp.all
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     *
     * @author zhy
     */
    private object SharedPreferencesCompat {
        private val sApplyMethod = findApplyMethod()

        /**
         * 反射查找apply的方法
         *
         * @return
         */
        private fun findApplyMethod(): Method? {
            try {
                val clz: Class<*> = SharedPreferences.Editor::class.java
                return clz.getMethod("apply")
            } catch (e: NoSuchMethodException) {
            }
            return null
        }

        /**
         * 如果找到则使用apply执行，否则使用commit
         *
         * @param editor
         */
        fun apply(editor: SharedPreferences.Editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor)
                    return
                }
            } catch (e: IllegalArgumentException) {
            } catch (e: IllegalAccessException) {
            } catch (e: InvocationTargetException) {
            }
            editor.commit()
        }
    }

    //返回String值
    fun getString(key: String?, defaultStr: String?): String? {
        return sp.getString(key, defaultStr)
    }

}